package com.ruoyi.user.controller;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.UserContext;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.user.domain.User;
import com.ruoyi.user.service.IUserCacheService;
import com.ruoyi.user.service.IUserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import cn.hutool.core.util.ObjectUtil;

@RestController
@RequestMapping("/app/user")
public class IUserController extends BaseController {

    @Resource
    IUserService userService;

    @Autowired
    IUserCacheService userCacheService;

    /**
     * 注册用户
     * @param user
     * @return
     */

    @PostMapping("/add")
    public AjaxResult add(@RequestBody User user){
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改密码
     * @param user
     * @return
     */

    @RequestMapping("/edit")
    public AjaxResult edit(@RequestBody User user){
        user.setId(UserContext.getUserId());
        return success(userService.updatePassword(user));
    }



    /**
     * 修改昵称
     * @param user
     * @return
     */

    @RequestMapping("/update")
    public AjaxResult update(@RequestBody User user){
        return success(userService.updateUserName(user));
    }

    /**
     * 获取用户信息
     * @return
     */
    @RequestMapping("/getInfo")
    public AjaxResult getInfo()
    {
        User user = new User();
        BeanUtil.copyProperties(UserContext.get(),user);
        return success(userService.getUserByPhone(user));
    }

    /**
     * 登录
     * @param user
     * @return
     */
    @RequestMapping("/login")
    public AjaxResult login(@RequestBody User user)
    {
        Long userId = userService.getLogin(user);
        if(ObjectUtil.isNotNull(userId)) {
            String token = IdUtils.randomUUID();
            userCacheService.login(token,userId);
            User u = userService.getUserByUserId(userId);
            u.setToken(token);
            return success(u);
        }
        return error();
    }



}
